package com.qiantu.phone.ui.activity;

import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.hjq.base.BaseDialog;
import com.hjq.http.listener.HttpCallback;
import com.qiantu.api.db.LLControllerDBManager;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.entity.ControllerBean;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.exception.ResultException;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.api.utils.ThemeUtil;
import com.qiantu.confignetwork.hiflying.aplink.LinkedModule;
import com.qiantu.confignetwork.hiflying.aplink.LinkingError;
import com.qiantu.confignetwork.hiflying.aplink.LinkingProgress;
import com.qiantu.confignetwork.hiflying.aplink.OnLinkListener;
import com.qiantu.confignetwork.hiflying.aplink.v1.ApLinker;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;

import java.io.IOException;

import okhttp3.Call;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import pl.droidsonroids.gif.GifTextView;

/**
 * time   : 2021/12/22
 */
public class AddDevice3Activity extends AppActivity implements OnLinkListener {

    private static final String TAG = "AddDevice3Activity";
    private GifImageView addStepBigGifView;
    private GifTextView stepFind;
    private View stepRegisterLine;
    private GifTextView stepRegister;
    private TextView tvExecute;
    private LinearLayout smallGif;
    private View stepInitLine;
    private GifTextView stepInit;
    private String deviceSn;
    //验证码
    private String validateCode;

    private String deviceMac;
    private int productLinkType;
    private String houseSerialNo;
    private Handler mHandler = new Handler();
    private ApLinker mApLinker;
    private String ssid;
    private String password;
    private int step;
    private int totalTime = 300 * 1000;
    private GifDrawable gifFindDrawable;
    private GifDrawable gifFindBigDrawable;
    private GifDrawable gifRegisterDrawable;
    private GifDrawable gifRegisterBigDrawable;
    private GifDrawable gifInitDrawable;
    private GifDrawable gifInitBigDrawable;
    private long startTime;
    private boolean isTimeOut;
    private boolean if_anewWiFi;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_device3;
    }

    @Override
    protected void initView() {
        addStepBigGifView = findViewById(R.id.add_step_big_gif_view);
        smallGif = findViewById(R.id.ll_small_gif);
        stepFind = findViewById(R.id.step_find);
        stepRegisterLine = findViewById(R.id.step_register_line);
        stepRegister = findViewById(R.id.step_register);
        stepInitLine = findViewById(R.id.step_init_line);
        stepInit = findViewById(R.id.step_init);
        tvExecute = findViewById(R.id.tv_execute);
        deviceSn = getIntent().getStringExtra("deviceSn");
        validateCode = getIntent().getStringExtra("validateCode");
        productLinkType = getIntent().getIntExtra("productLinkType", 0);
        ssid = getIntent().getStringExtra(SetNetWorkWifiActivity.WIFI_SSID);
        password = getIntent().getStringExtra(SetNetWorkWifiActivity.WIFI_PASSWORD);
        if_anewWiFi = getIntent().getBooleanExtra("if_anewWiFi",false);
        //重联网标识
        if (if_anewWiFi){
            tvExecute.setText(getResources().getString(R.string.wifi_execute));
        }
        start();


//        showConfirmHintDialog(R.string.add_device_find_error_hint);
    }

    @Override
    protected void initData() {

    }

    private void setStep(int step) {
        this.step = step;
        switch (this.step) {
            case 0:
                //停止注册小动画
                if (gifRegisterDrawable != null) {
                    gifRegisterDrawable.stop();
                }
                //停止初始化小动画
                if (gifInitDrawable != null) {
                    gifInitDrawable.stop();
                }
                //设置发现小动画
                if (gifFindDrawable == null) {
                    try {
                        int id = AppApplication.getInstance().getResourceId("gif_add_device_find" + "_" + ThemeUtil.getIconThemeSuffix().replace("/", ""), "drawable");
                        gifFindDrawable = new GifDrawable(getResources(), id);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                gifFindDrawable.reset();
                stepFind.setCompoundDrawablesWithIntrinsicBounds(null, gifFindDrawable, null, null);
                stepFind.setSelected(true);

                stepRegisterLine.setSelected(false);
                stepRegister.setCompoundDrawablesWithIntrinsicBounds(null, AppApplication.getInstance().getThemeDrawable(R.attr.icon_add_device_upload_gray), null, null);
                stepRegister.setSelected(false);
                stepInitLine.setSelected(false);
                stepInit.setCompoundDrawablesWithIntrinsicBounds(null, AppApplication.getInstance().getThemeDrawable(R.attr.icon_add_device_initialization_gray), null, null);
                stepInit.setSelected(false);

                //停止注册大图
                if (gifRegisterBigDrawable != null) {
                    gifRegisterBigDrawable.stop();
                }
                //停止初始化大图
                if (gifInitBigDrawable != null) {
                    gifInitBigDrawable.stop();
                }
                //设置发现大图
                if (gifFindBigDrawable == null) {
                    try {
                        int id = AppApplication.getInstance().getResourceId("gif_add_device_find_2" + (TextUtils.isEmpty(ThemeUtil.getIconThemeSuffix()) ? "" : "_") + ThemeUtil.getIconThemeSuffix().replace("/", ""), "drawable");
                        gifFindBigDrawable = new GifDrawable(getResources(), id);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                gifFindBigDrawable.reset();
                addStepBigGifView.setImageDrawable(gifFindBigDrawable);
                break;
            case 1:
                //停止发现小动画
                if (gifFindDrawable != null) {
                    gifFindDrawable.stop();
                }
                //停止初始化小动画
                if (gifInitDrawable != null) {
                    gifInitDrawable.stop();
                }

                stepFind.setCompoundDrawablesWithIntrinsicBounds(null, AppApplication.getInstance().getThemeDrawable(R.attr.icon_add_device_find), null, null);
                stepFind.setSelected(true);
                stepRegisterLine.setSelected(true);
                if (gifRegisterDrawable == null) {
                    try {
                        int id = AppApplication.getInstance().getResourceId("gif_add_device_upload" + (TextUtils.isEmpty(ThemeUtil.getIconThemeSuffix()) ? "" : "_") + ThemeUtil.getIconThemeSuffix().replace("/", ""), "drawable");
                        gifRegisterDrawable = new GifDrawable(getResources(), id);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                gifRegisterDrawable.reset();
                stepRegister.setCompoundDrawablesWithIntrinsicBounds(null, gifRegisterDrawable, null, null);
                stepRegister.setSelected(true);
                stepInitLine.setSelected(false);
                stepInit.setCompoundDrawablesWithIntrinsicBounds(null, AppApplication.getInstance().getThemeDrawable(R.attr.icon_add_device_initialization_gray), null, null);
                stepInit.setSelected(false);

                //停止发现大图
                if (gifFindBigDrawable != null) {
                    gifFindBigDrawable.stop();
                }
                //停止初始化大图
                if (gifInitBigDrawable != null) {
                    gifInitBigDrawable.stop();
                }
                //设置注册大图
                if (gifRegisterBigDrawable == null) {
                    try {
                        int id = AppApplication.getInstance().getResourceId("gif_add_device_upload_2" + (TextUtils.isEmpty(ThemeUtil.getIconThemeSuffix()) ? "" : "_") + ThemeUtil.getIconThemeSuffix().replace("/", ""), "drawable");
                        gifRegisterBigDrawable = new GifDrawable(getResources(), id);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                gifRegisterBigDrawable.reset();
                addStepBigGifView.setImageDrawable(gifRegisterBigDrawable);
                break;
            case 2:
                if (if_anewWiFi){
                    smallGif.setVisibility(View.GONE);
                }
                //停止发现小动画
                if (gifFindDrawable != null) {
                    gifFindDrawable.stop();
                }
                //停止注册小动画
                if (gifRegisterDrawable != null) {
                    gifRegisterDrawable.stop();
                }

                stepFind.setCompoundDrawablesWithIntrinsicBounds(null, AppApplication.getInstance().getThemeDrawable(R.attr.icon_add_device_find), null, null);
                stepFind.setSelected(true);
                stepRegisterLine.setSelected(true);
                stepRegister.setCompoundDrawablesWithIntrinsicBounds(null, AppApplication.getInstance().getThemeDrawable(R.attr.icon_add_device_upload), null, null);
                stepRegister.setSelected(true);
                stepInitLine.setSelected(true);
                if (gifInitDrawable == null) {
                    try {
                        int id = AppApplication.getInstance().getResourceId("gif_add_device_initialization" + (TextUtils.isEmpty(ThemeUtil.getIconThemeSuffix()) ? "" : "_") + ThemeUtil.getIconThemeSuffix().replace("/", ""), "drawable");
                        gifInitDrawable = new GifDrawable(getResources(), id);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                gifInitDrawable.reset();
                stepInit.setCompoundDrawablesWithIntrinsicBounds(null, gifInitDrawable, null, null);
                stepInit.setSelected(true);

                ///停止发现大图
                if (gifFindBigDrawable != null) {
                    gifFindBigDrawable.stop();
                }
                //停止注册大图
                if (gifRegisterBigDrawable != null) {
                    gifRegisterBigDrawable.stop();
                }
                //设置初始化大图
                if (gifInitBigDrawable == null) {
                    try {
                        int id = AppApplication.getInstance().getResourceId("gif_add_device_initialization_2" + (TextUtils.isEmpty(ThemeUtil.getIconThemeSuffix()) ? "" : "_") + ThemeUtil.getIconThemeSuffix().replace("/", ""), "drawable");
                        gifInitBigDrawable = new GifDrawable(getResources(), id);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                gifInitBigDrawable.reset();
                addStepBigGifView.setImageDrawable(gifInitBigDrawable);
                break;
        }
    }

    private void start() {
        isTimeOut = false;
        startTime = System.currentTimeMillis();
        post(countRunnable);
        if (if_anewWiFi){
            setStep(2);
        }else {
            setStep(0);
        }

        houseSerialNo = AppApplication.getInstance().getCurHouseInfo().getHouseSerialNo();
        switch (productLinkType) {
            case 1:
                registerDevice();
                break;
            case 2:
                configWifi();
                break;
        }
    }



    private Runnable countRunnable = new Runnable() {
        @Override
        public void run() {
            if(System.currentTimeMillis() - startTime > totalTime){
                isTimeOut = true;
                stopGifAndShowFailed(true);
            }else{
                postDelayed(this, 990);
            }
        }
    };

    private void configWifi() {
        mApLinker = ApLinker.getInstance(this);
        mApLinker.init();
        mApLinker.setOnLinkListener(this);
        mApLinker.setSsid(ssid);
        mApLinker.setPassword(password);
        mApLinker.setTimeoutPeriod(180 * 1000);
        mApLinker.setApPassword(null);
        mApLinker.start();

    }

    private void registerDevice() {
        if (!if_anewWiFi){
            setStep(1);
        }

        switch (productLinkType) {
            case 1:
                LLHttpManager.addControllerByWired(this, null,validateCode,deviceSn, houseSerialNo, new HttpCallback<HttpData<ControllerBean>>(this) {
                    @Override
                    public void onStart(Call call) {

                    }

                    @Override
                    public void onSucceed(HttpData<ControllerBean> result) {
                        if (result.isRequestSucceed() && !isTimeOut) {
                            saveDataAndToSuccess(result.getData());
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        handleException(e);
                    }

                    @Override
                    public void onEnd(Call call) {

                    }
                });
                break;
            case 2:
                LLHttpManager.addControllerByWifi(this, null, deviceMac, houseSerialNo, new HttpCallback<HttpData<ControllerBean>>(this) {
                    @Override
                    public void onStart(Call call) {

                    }

                    @Override
                    public void onSucceed(HttpData<ControllerBean> result) {

                        if (result.isRequestSucceed() && !isTimeOut) {
                            saveDataAndToSuccess(result.getData());
                        }
                    }

                    @Override
                    public void onFail(Exception e) {
                        handleException(e);
                    }

                    @Override
                    public void onEnd(Call call) {

                    }
                });
                break;
        }
    }

    private void handleException(Exception e) {
        if (e instanceof ResultException) {
            ResultException resultException = (ResultException) e;
            if (resultException.getHttpData().getCode() == 90008){
                //鉴权失败的判断
                toast(resultException.getHttpData().getMessage());
                stopGifAndShowFailed(true);
            }else if (resultException.getHttpData().getCode() == 20109
                    || resultException.getHttpData().getCode() == 20108
                    || resultException.getHttpData().getCode() == 20111) {
                toast(resultException.getHttpData().getMessage());
                stopGifAndShowFailed(true);
            } else if(resultException.getHttpData().getCode() == 20134){
                stopGifAndShowFailed(false);
                //wifi更换之后判断
                if (if_anewWiFi){
                    Intent intent = new Intent(getContext(), AddDeviceSuccessActivity.class);
                    intent.putExtra("controllerSerialNo", "1");
                    intent.putExtra("controllerName", "1");
                    intent.putExtra("controllerImageUrl", "https://dev-config.obs.cn-east-2.myhuaweicloud.com/product/QGkiRrFWows.png");

                    startActivity(intent);
                }else {
                    showErrorHintDialog(getString(R.string.device_has_added_hint));
                }

            } else if(resultException.getHttpData().getCode() == 20135){
                stopGifAndShowFailed(false);
                showErrorHintDialog(getString(R.string.device_has_added_by_other_hint));
            }else {
                postQuery();
            }
        } else {
            postQuery();
        }
    }

    private void postQuery() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                registerDevice();
            }
        }, 1000);
    }

    private void saveDataAndToSuccess(ControllerBean controller) {
        setStep(2);
        try {
            LLControllerDBManager.getInstance(getContext()).put(controller);
            LLDeviceDBManager.getInstance(getContext()).addBatch(controller.getDeviceItems());
            Intent intent = new Intent(getContext(), AddDeviceSuccessActivity.class);
            intent.putExtra("controllerSerialNo", controller.getControllerSerialNo());
            intent.putExtra("controllerName", controller.getName());
            intent.putExtra("controllerImageUrl", controller.getImageUrl());
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
            stopGifAndShowFailed(true);
        }
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;

    private void showConfirmHintDialog(String text) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setLeftBtnText(getString(R.string.cancel))
                    .setRightBtnText(getString(R.string.retry))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            finish();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            start();
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
//        mConfirmHintDialogBuilder.setCancelable(false);
//        mConfirmHintDialogBuilder.setCanceledOnTouchOutside(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void showErrorHintDialog(String text) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            finish();
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
//        mConfirmHintDialogBuilder.setCancelable(false);
//        mConfirmHintDialogBuilder.setCanceledOnTouchOutside(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void stopGifAndShowFailed(boolean isShow) {
        switch (step) {
            case 0:
                if (gifFindDrawable != null) {
                    gifFindDrawable.stop();
                }
                if (gifFindBigDrawable != null) {
                    gifFindBigDrawable.stop();
                }
                if(isShow){
                    showConfirmHintDialog(getString(R.string.add_device_find_error_hint));
                }
                break;
            case 1:
                if (gifRegisterDrawable != null) {
                    gifRegisterDrawable.stop();
                }
                if (gifRegisterBigDrawable != null) {
                    gifRegisterBigDrawable.stop();
                }
                if(isShow) {
                    showConfirmHintDialog(getString(R.string.add_device_register_error_hint));
                }
                break;
            case 2:
                if (gifInitDrawable != null) {
                    gifInitDrawable.stop();
                }
                if (gifInitBigDrawable != null) {
                    gifInitBigDrawable.stop();
                }
                if(isShow) {
                    showConfirmHintDialog(getString(R.string.add_device_init_error_hint));
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        if (gifFindDrawable != null) {
            gifFindDrawable.recycle();
        }
        if (gifFindBigDrawable != null) {
            gifFindBigDrawable.recycle();
        }
        if (gifRegisterDrawable != null) {
            gifRegisterDrawable.recycle();
        }
        if (gifRegisterBigDrawable != null) {
            gifRegisterBigDrawable.recycle();
        }
        if (gifInitDrawable != null) {
            gifInitDrawable.recycle();
        }
        if (gifInitBigDrawable != null) {
            gifInitBigDrawable.recycle();
        }
    }

    @Override
    public void onWifiConnectivityChangedBeforeLink(boolean connected, String ssid, WifiInfo wifiInfo) {
        Log.i(TAG, "onWifiConnectivityChangedBeforeLink connected:" + connected + " ssid:" + ssid);
    }

    @Override
    public void onLinked(@NonNull LinkedModule module) {
        mApLinker.stop();
        deviceMac = module.getMac();
//        if (deviceMac != null && deviceMac.contains(":")) {
//            return;
//        }
//        StringBuilder sb = new StringBuilder(deviceMac);
//        int offset = 2;
//        while (true) {
//            if (offset >= sb.length()) {
//                break;
//            }
//            sb.insert(offset, ":");
//            offset = offset + 3;
//        }
//        deviceMac = sb.toString();
        registerDevice();
    }

    @Override
    public void onFinished() {
        //配网task结束，不论结果成功失败超时都会调佣
        Log.i(TAG, "onFinished");
        mApLinker.stop();
    }

    @Override
    public void onWifiConfigTimeOut() {
        Log.i(TAG, "onTimeOut");
        mApLinker.stop();
        stopGifAndShowFailed(true);
    }

    @Override
    public void onError(LinkingError error) {
        Log.i(TAG, "onError: " + error);
        mApLinker.stop();
        stopGifAndShowFailed(true);
    }

    @Override
    public void onProgress(LinkingProgress progress) {
        Log.i(TAG, "onProgress: " + progress);
        if (progress == LinkingProgress.CONFIG_AP) {
        }
    }
}